package com.feng.dt.quartz.job;

import com.feng.common.spring.ApplicationContextHolder;
import com.feng.dt.model.entity.ScheduleJob;
import com.feng.dt.model.entity.ScheduleJobLog;
import com.feng.dt.model.enums.Exe_statusEnum;
import com.feng.dt.service.ScheduleJobLogService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Lee
 */
public class QuartzJob extends QuartzJobBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzJob.class);

    private ExecutorService threadPool = Executors.newFixedThreadPool(2);

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        long startTime = System.currentTimeMillis();
        long endTime = 0;
        ScheduleJobLog log = new ScheduleJobLog();
        ScheduleJobLogService scheduleJobLogService = ApplicationContextHolder.getBean(ScheduleJobLogService.class);
        try {
            ScheduleJob scheduleJob = (ScheduleJob) jobExecutionContext.getMergedJobDataMap().get("JOB_PARAM_KEY");
            int jobId = scheduleJob.getJobId();
            LOGGER.info("---------------------------------------------");
            LOGGER.info("准备执行任务，任务id：" + jobId);

            LOGGER.info("target={}",scheduleJob.getBeanName());
            LOGGER.info("methodName={}",scheduleJob.getMethodName());
            LOGGER.info("params={}",scheduleJob.getParams());

            log.setBeanName(scheduleJob.getBeanName());
            log.setMethodName(scheduleJob.getMethodName());
            log.setJobId(scheduleJob.getJobId());
            log.setParams(scheduleJob.getParams());
            log.setExeStatus(Exe_statusEnum.SUCCESS);

            ScheduleRunnable scheduleRunnable = new ScheduleRunnable(scheduleJob.getBeanName(),scheduleJob.getMethodName(),scheduleJob.getParams());
            threadPool.execute(scheduleRunnable);

            LOGGER.info("任务执行结束，任务id：" + jobId);
            LOGGER.info("---------------------------------------------");

            LOGGER.info("总耗时：" + (endTime - startTime) + "毫秒");
        } catch (Exception e) {
            LOGGER.info("任务执行失败，任务id："  + jobExecutionContext.getMergedJobDataMap().get("JOB_PARAM_KEY"));
            e.printStackTrace();
            log.setExeStatus(Exe_statusEnum.FAILURE);
            log.setErrorMessage(e.getMessage());
        } finally {
            endTime = System.currentTimeMillis();
            log.setTimes(endTime - startTime);
            log.fillDefaultValues();
            scheduleJobLogService.save(log);
        }
    }
}
